<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 6.3.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon.jpg">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon.jpg">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"matian.connorma.cn","root":"/","scheme":"Muse","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":false,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}}};
  </script>

  <meta name="description" content="ConcurrentHashMap 的实现比较复杂，里面涉及到的内容很多，而且有很多的性能优化的策略，想全部搞清楚比较困难，所以主要对里面感兴趣的并发的处理方面，相关的几个函数的实现看下，难免有理解不到位的地方，以后随时修改补充吧。 这里看的是 java 7 中的实现。 另外，推荐一篇文章，写的很详细： The Concurrency Of ConcurrentHashMap">
<meta property="og:type" content="article">
<meta property="og:title" content="ConcurrentHashMap源码学习（java 7）">
<meta property="og:url" content="http://matian.connorma.cn/31d2f121.html">
<meta property="og:site_name" content="马天">
<meta property="og:description" content="ConcurrentHashMap 的实现比较复杂，里面涉及到的内容很多，而且有很多的性能优化的策略，想全部搞清楚比较困难，所以主要对里面感兴趣的并发的处理方面，相关的几个函数的实现看下，难免有理解不到位的地方，以后随时修改补充吧。 这里看的是 java 7 中的实现。 另外，推荐一篇文章，写的很详细： The Concurrency Of ConcurrentHashMap">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2019-06-29T04:26:25.000Z">
<meta property="article:modified_time" content="2024-01-25T12:19:17.205Z">
<meta property="article:author" content="马天">
<meta property="article:tag" content="java">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="http://matian.connorma.cn/31d2f121.html">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>ConcurrentHashMap源码学习（java 7） | 马天</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">马天</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a>

  </li>
  </ul>
</nav>




</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://matian.connorma.cn/31d2f121.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="马天">
      <meta itemprop="description" content="程序猿">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="马天">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          ConcurrentHashMap源码学习（java 7）
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2019-06-29 12:26:25" itemprop="dateCreated datePublished" datetime="2019-06-29T12:26:25+08:00">2019-06-29</time>
            </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/java/" itemprop="url" rel="index"><span itemprop="name">java</span></a>
                </span>
            </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <p>ConcurrentHashMap 的实现比较复杂，里面涉及到的内容很多，而且有很多的性能优化的策略，想全部搞清楚比较困难，所以主要对里面感兴趣的并发的处理方面，相关的几个函数的实现看下，难免有理解不到位的地方，以后随时修改补充吧。</p>
<p>这里看的是 java 7 中的实现。</p>
<p>另外，推荐一篇文章，写的很详细： <a target="_blank" rel="noopener" href="https://www.burnison.ca/articles/the-concurrency-of-concurrenthashmap">The Concurrency Of ConcurrentHashMap</a></p>
<span id="more"></span>

<h1 id="涉及到的并发相关内容"><a href="#涉及到的并发相关内容" class="headerlink" title="涉及到的并发相关内容"></a>涉及到的并发相关内容</h1><h2 id="内存屏障"><a href="#内存屏障" class="headerlink" title="内存屏障"></a>内存屏障</h2><p>内存屏障用于：</p>
<ul>
<li>内存屏障两侧的指令禁止重排序</li>
<li>load屏障令高速缓存失效，屏障之后的指令强制从主存加载数据；store令屏障前的高速缓存中的数据强制刷新到主存</li>
</ul>
<p>一个出现了无数次的表格，应该来自《Java并发编程的艺术》：</p>
<table>
<thead>
<tr>
<th>屏障类型</th>
<th>屏障类型</th>
<th>说明</th>
</tr>
</thead>
<tbody><tr>
<td>LoadLoad Barriers</td>
<td>Load1;LoadLoad;Load2</td>
<td>确保 Load1 数据的装载先于 Load2 及所有后续装载指令的装载</td>
</tr>
<tr>
<td>StoreStore Barriers</td>
<td>Store1;StoreStore;Store2</td>
<td>确保 Store1 数据对其他处理器可见（刷新到内存）先于 Store2 及所有后续存储指令的存储</td>
</tr>
<tr>
<td>LoadStore Barriers</td>
<td>Load1;LoadStore;Store2</td>
<td>确保 Load1 数据装载先于 Store2 及所有后续的存储指令刷新到内存</td>
</tr>
<tr>
<td>StoreLoad Barriers</td>
<td>Store1;StoreLoad;Load2</td>
<td>确保 Store1 数据对其他处理器变得可见（指刷新到内存）先于 Load2 及所有后续装载指令的装载。StoreLoad Barriers 会使该屏障之前的所有内存访问指令（存储和装载指令）完成之后，才执行该屏障之后的内存访问指令</td>
</tr>
</tbody></table>
<p>举一个例子，对于 StoreLoad Barriers，有：Without StoreLoad barrier, a processor can write data only to its buffer without synchronizing with other processors (e.g. by writing to main memory), so another processor can then load the data either from its buffer or from main memory but will not get the most recent value.</p>
<h2 id="volatile"><a href="#volatile" class="headerlink" title="volatile"></a>volatile</h2><p>通过内存屏障实现 volatile 的内存语义，具体来说：</p>
<ul>
<li>在每个 volatile 写操作的前面插入一个 StoreStore 屏障</li>
<li>在每个 volatile 写操作的后面插入一个 StoreLoad 屏障</li>
<li>在每个 volatile 读操作的后面插入一个 LoadLoad 屏障</li>
<li>在每个 volatile 读操作的后面插入一个 LoadStore 屏障</li>
</ul>
<p>表现为：volatile 保证它修饰的变量的可见性，“当线程 A 首先写入一个 volatile 变量并且线程 B 随后读取该变量时，在写入 volatile 变量之前对 A 可见的所有变量，在 B 读取了 volatile 变量后，对 B 也是可见的”，“从内存可见性角度来看，写入 volatile 变量相当于退出同步代码块，而读取 volatile 变量就相当于进入同步代码块”。</p>
<p>但是要注意，volatile 修饰数组时，保证的是数组的引用的可见性，但数组元素的可见性是没有保证的。</p>
<h2 id="sun-misc-Unsafe-类提供的一些操作"><a href="#sun-misc-Unsafe-类提供的一些操作" class="headerlink" title="sun.misc.Unsafe 类提供的一些操作"></a>sun.misc.Unsafe 类提供的一些操作</h2><ol>
<li>CAS</li>
</ol>
<ul>
<li>即 compare and swap，CAS(V,A,B)，V 表示要更新的变量；A 是期望值，可以理解为，对于 变量V ，在 V &#x3D; A 的情况下，修改其值不会产生问题，那么 V 就是可以修改的（隐藏了ABA的问题，但没什么影响，实在需要解决可以用 AtomicStampedReference）；B 是要修改成的目标值。CAS(V,A,B)将返回是否修改成功，修改失败的情况下，该线程可以继续尝试修改（乐观锁）；</li>
<li>整个 CAS 过程对应的一条 CPU 指令，是原子操作；</li>
</ul>
<ol start="2">
<li><p>getObjectVolatile，volatile 读；</p>
</li>
<li><p>putObjectVolatile，volatile 写；</p>
</li>
<li><p>putOrderedObject，可看作是 putObjectVolatile 的延时版本，写入不一定对其他线程立即可见，但是相比 volatile 写操作，可以减小性能代价。因为，实际上，它对应的是 StoreStore 内存屏障而不是 StoreLoad。</p>
</li>
</ol>
<h1 id="数据结构"><a href="#数据结构" class="headerlink" title="数据结构"></a>数据结构</h1><p>ConcurrentHashMap 维护一个 Segment 的数组 segments，每个 Segment 维护一个 table 数组，数组元素是 HashEntry，HashEntry 则是链表的一个节点。可以将 Segment 看作一个 HashMap。</p>
<h1 id="处理并发的基本思路"><a href="#处理并发的基本思路" class="headerlink" title="处理并发的基本思路"></a>处理并发的基本思路</h1><p>使用分段锁来减小锁的粒度，即，需要对某个 key 所在的节点加锁时，对它所在的 Segment 加锁，这样其他 Segment 仍然可由其他线程安全的并发写入。这与之前的简单的全局互斥锁封装的 Synchronized*** 相比，类似于数据库中的行锁和表锁，增加了并发量。</p>
<p>只对写操作（put、remove、clear、rehash 等）和必要时的 size() 计数加锁，读操作不加锁，依靠 volatile 和 UNSAFE 类提供的 getObjectVolatile() 等操作实现。</p>
<p>很多的使用了 putOrderedObject() 代替 volatile 写来优化性能，，虽然会牺牲一些一致性。</p>
<h1 id="初始化-Segment"><a href="#初始化-Segment" class="headerlink" title="初始化 Segment"></a>初始化 Segment</h1><p>默认创建 16 个 Segment，并且数组 segments 是 final 变量，不会进行扩容。在初始化 map 时只会初始化 segments[0]，其他 Segment 在需要时以 segments[0] 作为模板创建。一旦创建后，segments 和 segments[i] 的引用将不会再修改，作为一个只读量来保证线程安全性。</p>
<p>初始化 segments 和 segments[0] 时，代码如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// create segments and segments[0]</span></span><br><span class="line">Segment&lt;K,V&gt; s0 =</span><br><span class="line">    <span class="keyword">new</span> <span class="title class_">Segment</span>&lt;K,V&gt;(loadFactor, (<span class="type">int</span>)(cap * loadFactor),</span><br><span class="line">                    (HashEntry&lt;K,V&gt;[])<span class="keyword">new</span> <span class="title class_">HashEntry</span>[cap]);</span><br><span class="line">Segment&lt;K,V&gt;[] ss = (Segment&lt;K,V&gt;[])<span class="keyword">new</span> <span class="title class_">Segment</span>[ssize];</span><br><span class="line">UNSAFE.putOrderedObject(ss, SBASE, s0); <span class="comment">// ordered write of segments[0]</span></span><br><span class="line"><span class="built_in">this</span>.segments = ss;</span><br></pre></td></tr></table></figure>

<p>要注意的是，这里使用的是 putOrderedObject 来写入 segments[0]，因此对其他线程可能不会立即可见。</p>
<h1 id="put、ensureSegment-与-rehash"><a href="#put、ensureSegment-与-rehash" class="headerlink" title="put、ensureSegment 与 rehash"></a>put、ensureSegment 与 rehash</h1><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> V <span class="title function_">put</span><span class="params">(K key, V value)</span> &#123;</span><br><span class="line">    Segment&lt;K,V&gt; s;</span><br><span class="line">    <span class="keyword">if</span> (value == <span class="literal">null</span>)</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> <span class="title class_">NullPointerException</span>();</span><br><span class="line">    <span class="type">int</span> <span class="variable">hash</span> <span class="operator">=</span> hash(key);</span><br><span class="line">    <span class="type">int</span> <span class="variable">j</span> <span class="operator">=</span> (hash &gt;&gt;&gt; segmentShift) &amp; segmentMask;</span><br><span class="line">    <span class="keyword">if</span> ((s = (Segment&lt;K,V&gt;)UNSAFE.getObject <span class="comment">// #1         // nonvolatile; recheck</span></span><br><span class="line">         (segments, (j &lt;&lt; SSHIFT) + SBASE)) == <span class="literal">null</span>) <span class="comment">//  in ensureSegment</span></span><br><span class="line">        s = ensureSegment(j);</span><br><span class="line">    <span class="keyword">return</span> s.put(key, hash, value, <span class="literal">false</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>如上述，一旦创建后，segments 和 segments[i] 的引用将不会再修改，作为一个只读量来保证线程安全性，所以 #1 处的判断，如果读到的 s 不是 null，那么 s 必然是已经初始化的。这里先进行一个这样的判断而不是直接执行 volatile 读，是减小 volatile 读在性能上的影响。</p>
<p>但是读到的 s 是 null 时，如注释所说，这是“nonvolatile”的，因为这里读取 s 是使用的 UNSAFE.getObject()。因此，在 ensureSegment() 中使用 UNSAFE.getObjectVolatile() 再次检查了 segments 中的值，在写入前仍然要进行检查。而且，和双重校验锁的单例模式的实现类似，双重校验锁最终在同步代码块中检查了要修改的元素的值，在这里，写入 segments 时，依靠 CAS 来保证正确的写入，并且将 CAS 放在 while 循环中，保证一定写入成功，更新的 segments 的元素对其他线程是可见的。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">private</span> Segment&lt;K,V&gt; <span class="title function_">ensureSegment</span><span class="params">(<span class="type">int</span> k)</span> &#123;</span><br><span class="line">    <span class="keyword">final</span> Segment&lt;K,V&gt;[] ss = <span class="built_in">this</span>.segments;</span><br><span class="line">    <span class="type">long</span> <span class="variable">u</span> <span class="operator">=</span> (k &lt;&lt; SSHIFT) + SBASE; <span class="comment">// raw offset</span></span><br><span class="line">    Segment&lt;K,V&gt; seg;</span><br><span class="line">    <span class="keyword">if</span> ((seg = (Segment&lt;K,V&gt;)UNSAFE.getObjectVolatile(ss, u)) == <span class="literal">null</span>) &#123;</span><br><span class="line">        Segment&lt;K,V&gt; proto = ss[<span class="number">0</span>]; <span class="comment">// use segment 0 as prototype</span></span><br><span class="line">        <span class="type">int</span> <span class="variable">cap</span> <span class="operator">=</span> proto.table.length;</span><br><span class="line">        <span class="type">float</span> <span class="variable">lf</span> <span class="operator">=</span> proto.loadFactor;</span><br><span class="line">        <span class="type">int</span> <span class="variable">threshold</span> <span class="operator">=</span> (<span class="type">int</span>)(cap * lf);</span><br><span class="line">        HashEntry&lt;K,V&gt;[] tab = (HashEntry&lt;K,V&gt;[])<span class="keyword">new</span> <span class="title class_">HashEntry</span>[cap];</span><br><span class="line">        <span class="keyword">if</span> ((seg = (Segment&lt;K,V&gt;)UNSAFE.getObjectVolatile(ss, u))</span><br><span class="line">            == <span class="literal">null</span>) &#123; <span class="comment">// recheck</span></span><br><span class="line">            Segment&lt;K,V&gt; s = <span class="keyword">new</span> <span class="title class_">Segment</span>&lt;K,V&gt;(lf, threshold, tab);</span><br><span class="line">            <span class="keyword">while</span> ((seg = (Segment&lt;K,V&gt;)UNSAFE.getObjectVolatile(ss, u))</span><br><span class="line">                    == <span class="literal">null</span>) &#123;</span><br><span class="line">                <span class="keyword">if</span> (UNSAFE.compareAndSwapObject(ss, u, <span class="literal">null</span>, seg = s))</span><br><span class="line">                    <span class="keyword">break</span>;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> seg;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>找到&#x2F;创建了 Segment 后，将进行 put 操作。</p>
<p>首先尝试获取锁：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">HashEntry&lt;K,V&gt; node = tryLock() ? <span class="literal">null</span> :</span><br><span class="line">    scanAndLockForPut(key, hash, value);</span><br></pre></td></tr></table></figure>

<p>如果直接获取到锁，直接向下执行；不然，会进入 scanAndLockForPut()，等待获取锁，同时在其中会定位应当放入的新节点在 table 中的位置，找到应插入的链表的头节点，遍历这一链表尝试寻找相同 key 的节点，如果找不到则预先创建一个 node，这个 node 将在后续获取到锁之后直接使用，执行这一遍历有两个优势：</p>
<ul>
<li>遍历链表，可以将链表加载到缓存，后续操作得到性能上的提升</li>
<li>如果要插入的 key 不存在，预先创建一个 node，后续插入时直接使用</li>
</ul>
<p>scanAndLockForPut() 将在获取到锁后返回，使用头插法进行插入。获取链表的头节点时，使用的是 entryAt() 函数，通过 UNSAFE.getObjectVolatile() 从 table 中读取链表的头节点。虽然 table 的引用是 volatile 的，但是 table 中的元素并不是，为了保证可见性，需要使用 UNSAFE.getObjectVolatile() 执行 volatile 读。</p>
<p>与 HashMap 类似，某个 Segment 内的元素数量超过了 threshold 时，会进行扩容，将 table 数组容量扩容为原来的两倍，之后定位索引的方式与 HashMap 是一致的，可参看<a href="/1d720228.html" title="令人惊叹的HashMap—数据结构与hash函数">令人惊叹的HashMap—数据结构与hash函数</a>。因为使用了可重入锁，rehash() 也只有从 put 函数进入这一个入口，也是加锁的。需要留意的是 rehash 操作在遍历链表时，首先执行了这样一段代码：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">HashEntry&lt;K,V&gt; lastRun = e;</span><br><span class="line"><span class="type">int</span> <span class="variable">lastIdx</span> <span class="operator">=</span> idx;</span><br><span class="line"><span class="keyword">for</span> (HashEntry&lt;K,V&gt; last = next;</span><br><span class="line">    last != <span class="literal">null</span>;</span><br><span class="line">    last = last.next) &#123;</span><br><span class="line">    <span class="type">int</span> <span class="variable">k</span> <span class="operator">=</span> last.hash &amp; sizeMask;</span><br><span class="line">    <span class="keyword">if</span> (k != lastIdx) &#123;</span><br><span class="line">        lastIdx = k;</span><br><span class="line">        lastRun = last;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">newTable[lastIdx] = lastRun;</span><br></pre></td></tr></table></figure>

<p>这一段代码是用来“Reuse consecutive sequence at same slot”：在遍历中尝试找到一个节点 lastRun，从这一个节点开始的之后的所有节点，都不需要移动位置，这一个操作看似多余，但其实“Statistically, at the default threshold, only about one-sixth of them need cloning when a table doubles.”</p>
<h1 id="remove"><a href="#remove" class="headerlink" title="remove"></a>remove</h1><p>首先调用 segmentForHash() 函数，segmentForHash() 中使用 UNSAFE.getObjectVolatile() 执行 volatile 读保证可见性，检查 key 应在的 Segment 是否为 null，如果是 null 那么一定没有存储这个 key。</p>
<p>如果找到了 key 所在的 Segment，将会尝试获得这一 Segment 的锁执行删除操作，尝试获得锁的过程与 put 操作类似。remove、put、rehash、clear 都是加锁的，所以不必担心它们之间的线程安全性。</p>
<p>之后定位要查找的节点在数组 table 中的位置，table 是 volatile 的，而且对 table 的引用在创建后只有 rehash 时才修改，所以不必担心 table 的引用的线程安全性。定位头节点使用的是 entryAt() 方法，内部是使用 UNSAFE.getObjectVolatile() 执行了 volatile 读操作，这是因为 table 引用本身是 volatile 的，但是数组元素的可见性并没有保证。</p>
<p>最终使用 setEntryAt() 和 setNext() 从链表中移除节点，都是使用了 UNSAFE.putOrderedObject()。因为释放锁时会写入更新的值，所以使用 UNSAFE.putOrderedObject() 相比 UNSAFE.putObjectVolatile() 只是在可见性上做出了一点牺牲，但是性能优化很多。</p>
<h1 id="get"><a href="#get" class="headerlink" title="get"></a>get</h1><p>get 函数的代码如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> V <span class="title function_">get</span><span class="params">(Object key)</span> &#123;</span><br><span class="line">    Segment&lt;K,V&gt; s; <span class="comment">// manually integrate access methods to reduce overhead</span></span><br><span class="line">    HashEntry&lt;K,V&gt;[] tab;</span><br><span class="line">    <span class="type">int</span> <span class="variable">h</span> <span class="operator">=</span> hash(key);</span><br><span class="line">    <span class="type">long</span> <span class="variable">u</span> <span class="operator">=</span> (((h &gt;&gt;&gt; segmentShift) &amp; segmentMask) &lt;&lt; SSHIFT) + SBASE;</span><br><span class="line">    <span class="keyword">if</span> ((s = (Segment&lt;K,V&gt;)UNSAFE.getObjectVolatile(segments, u)) != <span class="literal">null</span> &amp;&amp;</span><br><span class="line">        (tab = s.table) != <span class="literal">null</span>) &#123;</span><br><span class="line">        <span class="keyword">for</span> (HashEntry&lt;K,V&gt; e = (HashEntry&lt;K,V&gt;) UNSAFE.getObjectVolatile</span><br><span class="line">                 (tab, ((<span class="type">long</span>)(((tab.length - <span class="number">1</span>) &amp; h)) &lt;&lt; TSHIFT) + TBASE);</span><br><span class="line">             e != <span class="literal">null</span>; e = e.next) &#123;</span><br><span class="line">            K k;</span><br><span class="line">            <span class="keyword">if</span> ((k = e.key) == key || (e.hash == h &amp;&amp; key.equals(k)))</span><br><span class="line">                <span class="keyword">return</span> e.value;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="literal">null</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>首先要明确的是对 get 等方法的行为的许诺：“Retrievals reflect the results of the most recently completed update operations holding upon their onset.”，也就是说，get 函数得到的结果，是最近完成的更新的结果，但是因为 get 是不加锁的，可能同时存在 put、remove 等操作，get 得到的不一定是最新的结果。</p>
<p>get 中将 tab 和 e 放在了局部变量中来访问，这导致失去一些一致性，可以看作是一种防御性的思路，首先保证正确性，这也能够满足做出的上述许诺。</p>
<p>比较关心的是 get 与 put、remove 的可见性问题。</p>
<p>get 与 put 并发时，插入节点是头插法，如果在插入新的头节点完成之后（因为 put 使用的是 UNSAFE.putOrderedObject()，所以理论上在 put 完成释放锁之后才保证对其他线程的可见性）进行查询，依赖于 UNSAFE.getObjectVolatile() 保证可见性；如果在插入头节点之前已经在进行 get，那么 get 将沿着链表查询，而新插入的头节点是不会考虑的；在需要 rehash 时，rehash 将更新 table 数组的引用，而 get 中使用局部变量 tab 保存了 table 的原引用，将在原数组上进行遍历。这也是符合上述许诺的。</p>
<p>get 与 remove 并发时，如果移除的是头节点，get 的情况与以上 put 时类似；如果移除的是其他节点，而此时 get 还未到达该节点，仍然通过 volatile 语义保证可见性，如果 get 已经经过了这一节点，那么自然也不会对查询结果有影响。</p>

    </div>

    
    
    

      <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/java/" rel="tag"># java</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/a5d8fb53.html" rel="prev" title="Spring Boot 启动流程简记">
      <i class="fa fa-chevron-left"></i> Spring Boot 启动流程简记
    </a></div>
      <div class="post-nav-item">
    <a href="/6d9ffe57.html" rel="next" title="令人费解的ThreadLocal">
      令人费解的ThreadLocal <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#%E6%B6%89%E5%8F%8A%E5%88%B0%E7%9A%84%E5%B9%B6%E5%8F%91%E7%9B%B8%E5%85%B3%E5%86%85%E5%AE%B9"><span class="nav-number">1.</span> <span class="nav-text">涉及到的并发相关内容</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%86%85%E5%AD%98%E5%B1%8F%E9%9A%9C"><span class="nav-number">1.1.</span> <span class="nav-text">内存屏障</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#volatile"><span class="nav-number">1.2.</span> <span class="nav-text">volatile</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#sun-misc-Unsafe-%E7%B1%BB%E6%8F%90%E4%BE%9B%E7%9A%84%E4%B8%80%E4%BA%9B%E6%93%8D%E4%BD%9C"><span class="nav-number">1.3.</span> <span class="nav-text">sun.misc.Unsafe 类提供的一些操作</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84"><span class="nav-number">2.</span> <span class="nav-text">数据结构</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E5%A4%84%E7%90%86%E5%B9%B6%E5%8F%91%E7%9A%84%E5%9F%BA%E6%9C%AC%E6%80%9D%E8%B7%AF"><span class="nav-number">3.</span> <span class="nav-text">处理并发的基本思路</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E5%88%9D%E5%A7%8B%E5%8C%96-Segment"><span class="nav-number">4.</span> <span class="nav-text">初始化 Segment</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#put%E3%80%81ensureSegment-%E4%B8%8E-rehash"><span class="nav-number">5.</span> <span class="nav-text">put、ensureSegment 与 rehash</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#remove"><span class="nav-number">6.</span> <span class="nav-text">remove</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#get"><span class="nav-number">7.</span> <span class="nav-text">get</span></a></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">马天</p>
  <div class="site-description" itemprop="description">程序猿</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">41</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">17</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">25</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/matian2014" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;matian2014" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="mailto:matian1103@qq.com" title="E-Mail → mailto:matian1103@qq.com" rel="noopener" target="_blank"><i class="fa fa-envelope fa-fw"></i>E-Mail</a>
      </span>
  </div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        
  <div class="beian"><a href="https://beian.miit.gov.cn/" rel="noopener" target="_blank">陕ICP备2023001563号 </a>
  </div>

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2025</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">马天</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://muse.theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Muse</a> 强力驱动
  </div>

        








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/muse.js"></script>


<script src="/js/next-boot.js"></script>




  















  

  

</body>
</html>
